import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
// 引入提示组件
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
// 引入获取token的接口
import { userStoreInfo } from './user'
// 数据接口
import { addCartApi, getCartApi, delCartApi } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
    // 数据
    const cartList = ref([])
    // token
    const useStore = userStoreInfo()
    const token = ref('')
    token.value = computed(() => useStore.userInfo.token)
    // 得到数据

    // 抽离的获取重新获取数据的接口
    const updataNewCartList = async () => {
        // 获取接口
        const res = await getCartApi()
        // 覆盖原有的数据
        cartList.value = res.data.result
    }

    const addCartList = async (goods) => {
        const { skuId, count } = goods
        // computed 赋值 必须要点value才能拿到
        if (token.value.value) {
            // 添加接口
            await addCartApi({ skuId, count })
            // 从新获取数据
            updataNewCartList()
        } else {
            // 判断在已有的商品列表中是否已经包含了要添加的，有的话就让其count佳佳，反之push
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                item.count += goods.count
            } else {
                cartList.value.push(goods)
            }
        }
        // 提示
        ElMessage({ type: 'success', message: '添加成功' })
    }
    // 删除数据
    const delCart = async (id) => {
        if (token.value.value) {
            await delCartApi([id])
            // 从新获取数据
            updataNewCartList()
        } else {
            cartList.value = cartList.value.filter(item => item.skuId !== id)
        }
        // 提示
        ElMessage({ type: 'success', message: '删除成功' })
    }
    // 清空数据 在用户退出登录时
    const clearCart = () => {
        cartList.value = []
    }

    // 计算总件数
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    // 总价格
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
    // 切换选中状态
    const chCheck = (i, selected) => {
        // 筛选出符合条件的那一项数据
        const itme = cartList.value.find(item => item.skuId === i.skuId)
        itme.selected = selected
    }
    // 全选与非全选功能
    const isAllCheck = computed(() => cartList.value.every(item => item.selected))
    const allCheck = (selected) => cartList.value.forEach(item => item.selected = selected)
    // 已选择的商品数量
    const checkCart = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    // 已选商品的总价格
    const checkCartPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))

    return {
        cartList,
        addCartList,
        delCart,
        allCount,
        allPrice,
        chCheck,
        isAllCheck,
        allCheck,
        checkCart,
        checkCartPrice,
        clearCart,
        updataNewCartList
    }
}, {
    persist: true
})